package com.example.softwareconfigurationcoursedesign.Admin;

import com.example.softwareconfigurationcoursedesign.ShopPage.ProductService;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Random;
@WebServlet("/addProduct")
public class AddProductServlet extends HttpServlet {

    // 处理POST请求
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // 从请求参数获取商品信息
        String productName = request.getParameter("productName"); // 获取商品名称
        double productPrice = Double.parseDouble(request.getParameter("productPrice")); // 获取商品价格
        String productTag = request.getParameter("productTag"); // 获取商品标签
        String productDetail = request.getParameter("productDetail"); // 获取商品详情
        String productUrl = request.getParameter("productUrl"); // 获取商品图片URL
        int pStock = Integer.parseInt(request.getParameter("productStock")); // 获取商品库存

        // 生成一个18位的随机商品ID
        StringBuilder PID = new StringBuilder(); // 初始化StringBuilder
        Random random = new Random();
        for (int i = 0; i < 18; i++) {
            int digit = random.nextInt(10); // 生成0到9的随机数字
            PID.append(digit);
        }
        String productPid = PID.toString(); // 获取生成的商品ID
        System.err.println(productPid); // 打印生成的商品ID，可以删除或保留作为调试信息

        // 调用商品服务实现类的方法，将商品信息添加到数据库
        ProductServiceImplement productServiceImplement = new ProductService();
        productServiceImplement.addProduct(pStock, productPid, productName, productPrice, productTag, productDetail, productUrl);

        // 返回JavaScript脚本，关闭当前页面
        response.getWriter().println("<script>window.close();</script>");
    }
}

//        System.out.println("添加商品信息：");
//        System.out.println("商品名称：" + productName);
//        System.out.println("商品价格：" + productPrice);
//        System.out.println("商品标签：" + productTag);
//        System.out.println("商品详情：" + productDetail);
//        System.out.println("添加商品");